package com.neuronbit.businessflow.intellij.function;

import com.neuronbit.businessflow.intellij.editor.BpmHtmlFileEditor;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.jcef.JBCefJSQuery;
import org.cef.browser.CefBrowser;
import org.jetbrains.annotations.NotNull;

import java.util.function.Function;

/**
 * The type Save schema function.
 */
public class SaveSchemaFunction implements Function<String, JBCefJSQuery.Response> {
    private final Project project;
    private final VirtualFile file;
    private final CefBrowser cefBrowser;
    private final String viewerUrl;
    private Document document;

    /**
     * Instantiates a new Save schema function.
     *
     * @param project    the project
     * @param file       the file
     * @param cefBrowser the cef browser
     * @param viewerUrl  the viewer url
     */
    public SaveSchemaFunction(Project project, VirtualFile file, @NotNull CefBrowser cefBrowser, String viewerUrl) {
        this.project = project;
        this.file = file;
        this.cefBrowser = cefBrowser;
        this.viewerUrl = viewerUrl;
        ApplicationManager.getApplication().runReadAction(() -> {
            document = FileDocumentManager.getInstance().getDocument(file);
            if (null != document) {
                document.setReadOnly(false);
            }
        });
    }

    @Override
    public JBCefJSQuery.Response apply(String params) { // 2
        Logger.getInstance(BpmHtmlFileEditor.class).info("message from browser " + params);
//        GlobalSearchScope scope = GlobalSearchScope.allScope(project);
//        PsiClass psiClass = JavaPsiFacade.getInstance(project).findClass(params, scope);

//        ApplicationManager.getApplication().runWriteAction(() -> { //这里不能用这个，线程问题
        WriteCommandAction.runWriteCommandAction(project, () -> {
            document.setText(params);
            //FileDocumentManager.getInstance().saveDocument(document);
        });

        return null;
//
//        PsiClass psiClass = selectedPsiClass[0];
//        if (null != psiClass) {
//            return new JBCefJSQuery.Response(psiClass.getQualifiedName(), 0, "success"); // 3
//        }
//
//
//        return new JBCefJSQuery.Response("xyz", 0, "success"); // 3
    }
}
